local assets =
{
    Asset("ANIM", "anim/tornado.zip"),
}
--旋风
local brain = require("brains/tornadobrain")
local Tools = require 'util/tools'
local interval = 1
local attract_range =14
local dmg = 23
local function ontornadolifetime(inst)
    inst.task = nil
    inst.sg:GoToState("despawn")
end

local function SetDuration(inst, duration)
    if inst.task ~= nil then
        inst.task:Cancel()
    end
    inst.task = inst:DoTaskInTime(duration, ontornadolifetime)
end

local function OnLoad(inst, data)
    inst:Remove()
end

local function fn()
    local inst = CreateEntity()

    inst.entity:AddTransform()
    inst.entity:AddAnimState()
    inst.entity:AddSoundEmitter()
    inst.entity:AddNetwork()
    inst.entity:AddDynamicShadow()
    
    inst.DynamicShadow:SetSize(.8, .5)

    inst.AnimState:SetFinalOffset(2)
    inst.AnimState:SetBank("tornado")
    inst.AnimState:SetBuild("tornado")
    inst.AnimState:PlayAnimation("tornado_pre")
    inst.AnimState:PushAnimation("tornado_loop")
    inst.AnimState:SetMultColour(0.0, 0.784, 0.549,1)
    
    inst.AnimState:SetScale(3, 3)
    ---inst.AnimState:SetMultColour(1,0.8,0,0.8)

    inst.SoundEmitter:PlaySound("dontstarve_DLC001/common/tornado", "spinLoop")

    MakeInventoryPhysics(inst)
    RemovePhysicsColliders(inst)

    inst.entity:SetPristine()

    if not TheWorld.ismastersim then
        return inst
    end

    inst:AddComponent("knownlocations")

    inst:AddComponent("locomotor")
    inst.components.locomotor.walkspeed = TUNING.TORNADO_WALK_SPEED * .43
    inst.components.locomotor.runspeed = TUNING.TORNADO_WALK_SPEED

    inst:SetStateGraph("SGobsword_wind_torado")
    inst:SetBrain(brain)
    

    inst.WINDSTAFF_CASTER = nil
    inst.persists = false

    inst.SetDuration = SetDuration
    inst:SetDuration(10)
    --龙卷暴风吸入
    inst.task = inst:DoTaskInTime(1, function(inst)
        
       
        inst.task.period_attraction = inst:DoPeriodicTask(interval,function()
             local mouse_x,mouse_y,mouse_z = inst.Transform:GetWorldPosition()
            local ents = TheSim:FindEntities(mouse_x,mouse_y,mouse_z,attract_range,{'locomotor'},{'INLIMBO','inst','companion','wall',"player"})
            for _,v in pairs(ents or {}) do
                if v and v:IsValid() and v.components and v.components.health and not v.components.health:IsDead() then
                    local v_x,_,v_z = v.Transform:GetWorldPosition()
                    local dist = Tools:calcDist(v_x,v_z,mouse_x,mouse_z,true)
                    if dist > 1 then 
                        local des_x,des_z = Tools:findPointOnLine(v_x,v_z,mouse_x,mouse_z,dist,dist-1>0 and dist-1 or 1)
                        v.Physics:Teleport(des_x,0,des_z)
                    end
                    v.components.combat:GetAttacked(inst,dmg)
                end
            end
        end)
   
    end)
 
    inst.OnLoad = OnLoad

    return inst
end

return Prefab("obsword_wind_torado", fn, assets)